﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsmqNs = System.Messaging;

using WorkStation.Frameworks.EasyBus.MessageQueue;

namespace WorkStation.Frameworks.EasyBus.MessageQueue.Msmq
{
    /// <summary>
    /// MSMQ 终结点实现
    /// </summary>
    public class MsmqEndpoint : EndpointBase
    {
        public string Address { get; set; }

        public MsmqEndpoint(string address) 
        {
            this.Address = address;

            this.CheckEndpoint();
        }

        public override IChannel GetChannel()
        {
            return new MsmqChannel(this);
        }

        public override bool EndpointEqualsCore(object obj)
        {
            MsmqEndpoint endpoint = obj as MsmqEndpoint;

            if (endpoint.Address.ToUpper().Equals(this.Address.ToUpper()))
            {
                return true;
            }
            else 
            {
                return false;
            }
        }

        protected virtual void CheckEndpoint() 
        {
            MsmqNs.MessageQueue mq = null;

            try
            {
                if (this.Address.StartsWith(".") && !MsmqNs.MessageQueue.Exists(this.Address))
                {
                    mq = MsmqNs.MessageQueue.Create(this.Address);

                    while (!MsmqNs.MessageQueue.Exists(this.Address)) { System.Threading.Thread.Sleep(100); }
                    
                    mq.SetPermissions("Everyone", MsmqNs.MessageQueueAccessRights.FullControl, MsmqNs.AccessControlEntryType.Allow);
                }
            }
            catch (Exception ce)
            {
                throw ce;
            }
            finally 
            {
                if (mq != null) { mq.Dispose(); }
            }
        }
    }
}
